package com.tydic.trans.service.impl;

import com.tydic.trans.beans.Person;
import com.tydic.trans.mapper.DemoMapper;
import com.tydic.trans.service.DemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class DemoServiceImpl implements DemoService {
    @Autowired
    private DemoMapper demoMapper; //1.可以直接注入我们的DemoMapper 的Bean

    @Transactional(rollbackFor = {IllegalArgumentException.class}) //2.使用@Transactional 注解的rollbackFor 属性，指定特定异常时，数据回滚
    public Person savePersonWithRollBack(Person person) {
        boolean save = demoMapper.save(person);
        if (person.getName().equals("汪云飞")) {
            throw new IllegalArgumentException("汪云飞已存在，数据将回滚"); //3.硬编码手动触发异常
        }
        return person;
    }

    @Transactional(noRollbackFor = {IllegalArgumentException.class})
    //4.使用@Transactional 注解的noRollbackFor 属性，指定特定异常时，数据回滚
    public Person savePersonWithoutRollBack(Person person) {
        boolean save = demoMapper.save(person);
        if (person.getName().equals("汪云飞")) {
            throw new IllegalArgumentException("汪云飞虽已存在，数据将不会回滚");
        }
        return person;
    }
}
